﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Manger_ResourceAdd : System.Web.UI.Page
{
    string sMajorID;
    string sMajorName;
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie ck = Request.Cookies["major"];
        if (ck != null)
        {
            sMajorID = ck.Values["majorid"];
            sMajorName = HttpUtility.UrlDecode(ck.Values["majorname"]);
            XmlDataSource1.DataFile = "~/xml/ResourceType_" + sMajorID + ".xml";
            SqlDataSource2.SelectParameters.Add("Course_MajorID", sMajorID);
            if (!IsPostBack)
            {
                string rsid = Request.QueryString["rs_id"];
                if (rsid != null)
                {
                    SqlDataSource1.SelectCommand = "select Resource_Redirect, Resource_Type,Resource_TypeName,Resource_Size,Resource_Name,Resource_URL,Resource_Preview,Resource_Editor,Resource_Publish,Resource_From,Resource_Describe,Resource_KeyWord,Resource_EditDate from zyk_Resources where Resource_ID=@rsid";
                    SqlDataSource1.SelectParameters.Clear();
                    SqlDataSource1.SelectParameters.Add("rsid", TypeCode.Int16, rsid);
                    DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
                    if (dv.Count > 0)
                    {

                        lbTypePath.Text = dv[0]["Resource_Type"].ToString();
                        tbType.Text = dv[0]["Resource_TypeName"].ToString();
                        tbResourceName.Text = dv[0]["Resource_Name"].ToString();
                        tbResourceURL.Text = dv[0]["Resource_URL"].ToString();
                        tbWriter.Text = dv[0]["Resource_Editor"].ToString();
                        tbFileSize.Text = dv[0]["Resource_Size"].ToString();
                        preImage.ImageUrl = dv[0]["Resource_Preview"].ToString();
                        tbFrom.Text = dv[0]["Resource_From"].ToString();
                        tbKeyWord.Text = dv[0]["Resource_KeyWord"].ToString();
                        tbPublish.Text = dv[0]["Resource_Publish"].ToString();
                        tbEditDate.Text = dv[0]["Resource_EditDate"].ToString();
                        FCKeditor1.Value = dv[0]["Resource_Describe"].ToString();
                        tbRedirect.Text = dv[0]["Resource_Redirect"].ToString();
                        hfType.Value = rsid; //非0表示现在是编辑状态
                        btNewsAdd.Text = "更新资源";

                        fillListBox(rsid, ListBox2);


                    }

                }
            }

        }
        else
        {
            FormsAuthentication.SignOut();
            FormsAuthentication.RedirectToLoginPage();
        }
    }
    protected void fillListBox(string rsid,ListBox listbox)
    {
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["Jxzy_Database"].ToString();
        ds.SelectCommand = "select Course_ID,Course_Name from zyk_RCR inner join zyk_Courses on Course_ID=RCR_CourseID where RCR_ResourceID=@rsid";
        ds.SelectParameters.Add("rsid",rsid);
        DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);

        if (dv.Count > 0)
        {
            for (int i = 0; i < dv.Count; i++)
            {
                ListItem a=new ListItem();
                a.Value=dv[i]["Course_ID"].ToString();
                a.Text=dv[i]["Course_Name"].ToString();
                listbox.Items.Add(a);
            }
        }
        ds.Dispose();
        dv.Dispose();

    }
    protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {

        string sTextPath = TreeView1.SelectedNode.Text;
        string sValuePath = "{" + TreeView1.SelectedNode.Value + "}";
        TreeNode tn = TreeView1.SelectedNode;
        while (tn.Parent != null)
        {
            tn = tn.Parent;
            sTextPath = tn.Text + "->" + sTextPath;
            sValuePath = "{" + tn.Value + "}" + sValuePath;
        }
        tbType.Text = sTextPath;
        lbTypePath.Text = sValuePath;
       
        TreeView1.Visible = false;
    }
    protected void btSelect_Click(object sender, EventArgs e)
    {
        TreeView1.Visible = true;
    }
    protected void btNewsAdd_Click(object sender, EventArgs e)
    {

        if (FCKeditor1.Value.Length >= 4000)
        {
            Response.Write("<script >function window.onload() {alert('内容超过4000字符，请尽量清理格式。');}</script>");
            return;
        }
        if (hfType.Value == "0")
        {
            SqlDataSource1.InsertCommand = "insert into [zyk_Resources]([Resource_Redirect],[Resource_Type],[Resource_TypeName],[Resource_MajorID],[Resource_Name],[Resource_URL],[Resource_KeyWord],[Resource_Preview],[Resource_Describe],[Resource_Editor],[Resource_Publish],[Resource_EditDate],[Resource_From],[Resource_UserID],[Resource_Size])";
            SqlDataSource1.InsertCommand += " values(@redirect,@type,@typename,@majorid,@name,@url,@keyword,@preview,@describe,@editor,@publish,@editdate,@from,@userid,@size)";
            SqlDataSource1.InsertParameters.Add("redirect",tbRedirect.Text);
            SqlDataSource1.InsertParameters.Add("type", lbTypePath.Text);
            SqlDataSource1.InsertParameters.Add("typename", tbType.Text);
            SqlDataSource1.InsertParameters.Add("majorid", Request.Cookies["major"].Values["majorid"]);
            SqlDataSource1.InsertParameters.Add("name", tbResourceName.Text);
            SqlDataSource1.InsertParameters.Add("url", tbResourceURL.Text);
            SqlDataSource1.InsertParameters.Add("keyword", tbKeyWord.Text);
            SqlDataSource1.InsertParameters.Add("preview", preImage.ImageUrl);
            SqlDataSource1.InsertParameters.Add("describe", FCKeditor1.Value);
            SqlDataSource1.InsertParameters.Add("editor", tbWriter.Text);
            SqlDataSource1.InsertParameters.Add("publish", tbPublish.Text);
            SqlDataSource1.InsertParameters.Add("editdate", tbEditDate.Text);
            SqlDataSource1.InsertParameters.Add("from", tbFrom.Text);
            SqlDataSource1.InsertParameters.Add("userid", Page.User.Identity.Name);
            SqlDataSource1.InsertParameters.Add("size", tbFileSize.Text);
            SqlDataSource1.Insert();

            updateResourceCourse("0",ListBox2);
        }
        else
        {
            SqlDataSource1.UpdateCommand = "update [zyk_Resources] set [Resource_Redirect]=@redirect,[Resource_TypeName]=@typename,[Resource_Name]=@name,[Resource_URL]=@url,[Resource_KeyWord]=@keyword,";
            SqlDataSource1.UpdateCommand += " [Resource_Preview]=@preview,[Resource_Describe]=@describe,[Resource_Editor]=@editor,[Resource_Publish]=@publish,[Resource_Size]=@size,[Resource_EditDate]=@editdate,[Resource_From]=@from";
            SqlDataSource1.UpdateCommand += " where [Resource_ID]=@rsid";
            SqlDataSource1.UpdateParameters.Add("redirect", tbRedirect.Text);
            SqlDataSource1.UpdateParameters.Add("type", lbTypePath.Text);
            SqlDataSource1.UpdateParameters.Add("typename", tbType.Text);
            SqlDataSource1.UpdateParameters.Add("name", tbResourceName.Text);
            SqlDataSource1.UpdateParameters.Add("url", tbResourceURL.Text);
            SqlDataSource1.UpdateParameters.Add("keyword", tbKeyWord.Text);
            SqlDataSource1.UpdateParameters.Add("preview", preImage.ImageUrl);
            SqlDataSource1.UpdateParameters.Add("describe", FCKeditor1.Value);
            SqlDataSource1.UpdateParameters.Add("editor", tbWriter.Text);
            SqlDataSource1.UpdateParameters.Add("publish", tbPublish.Text);
            SqlDataSource1.UpdateParameters.Add("editdate", tbEditDate.Text);
            SqlDataSource1.UpdateParameters.Add("from", tbFrom.Text);
            SqlDataSource1.UpdateParameters.Add("size", tbFileSize.Text);
            SqlDataSource1.UpdateParameters.Add("rsid", TypeCode.Int32, hfType.Value);
            SqlDataSource1.Update();

            updateResourceCourse(hfType.Value, ListBox2);
        }
        Response.Redirect("Manger_ResourceList.aspx");
    }
    protected void updateResourceCourse(string rsid,ListBox listbox)
    {
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["Jxzy_Database"].ToString();
        ds.DeleteCommand = "delete from zyk_RCR where RCR_ResourceID=@rsid";
        ds.DeleteParameters.Add("rsid", rsid);
        ds.Delete();

        if (rsid == "0")
        {
            ds.SelectCommand = "select max(Resource_ID) as newid from zyk_Resources";
            DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
            rsid = dv[0][0].ToString();

        }
        
        ds.InsertCommand = "insert into zyk_RCR(RCR_CourseID,RCR_ResourceID) values(@courseid,@rsid)";
        for (int i = 0; i < listbox.Items.Count; i++)
        {
            
            ds.InsertParameters.Clear();
            ds.InsertParameters.Add("courseid", listbox.Items[i].Value);
            ds.InsertParameters.Add("rsid", rsid);
            ds.Insert();

        }

    }
    protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e)
    {
        if (e.AffectedRows == 1)
        {
            
          
                Response.Write("<script >function window.onload() {alert('资源添加成功!');}</script>");
        }
        else
        {
            Response.Write("<script >function window.onload() {alert('资源添加失败，请检查数据!');}</script>");
        }
    }
    protected void SqlDataSource1_Updated(object sender, SqlDataSourceStatusEventArgs e)
    {
        if (e.AffectedRows == 1)
        {
            Response.Write("<script >function window.onload() {alert('资源更新成功!');}</script>");

        }
        else
        {
            Response.Write("<script >function window.onload() {alert('资源更新失败，请检查数据!');}</script>");
        }
    }
    protected void btUpload_Click(object sender, EventArgs e)
    {

        try
        {
            if (FileUpload1.HasFile && lbTypePath.Text != "" && lbTypePath.Text != "{0}")
            {
                HttpCookie ck = Request.Cookies["major"];
                string savepath = ck.Values["majorid"] + "/" + lbTypePath.Text + "/";
                myUpload upload = new myUpload(FileUpload1, savepath);
                tbResourceURL.Text = upload.filePath;
                tbFileSize.Text = upload.fileSize.ToString();
            }
            else
            {
                throw new Exception("没有选择文件或保存目录。");
            }
        }
        catch (Exception ex)
        {
            Response.Write("<script >function window.onload() {alert('"+ex.Message.ToString()+"');}</script>");
        }
        
    }
    protected void Button4_Click(object sender, EventArgs e)
    {
        ListBox2.Items.Clear();
        
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        ListBox2.Items.Clear();
        for (int i = 0; i < ListBox1.Items.Count; i++)
        {
            ListBox2.Items.Add(ListBox1.Items[i]);
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        
        for (int i = 0; i < ListBox1.Items.Count; i++)
        {
            if (ListBox1.Items[i].Selected)
            {
                bool bFind = false;
                for (int j = 0; j < ListBox2.Items.Count; j++)
                {
                    if (ListBox1.Items[i].Value == ListBox2.Items[j].Value)
                        bFind = true;
                }
                if (bFind != true)
                    ListBox2.Items.Add(ListBox1.Items[i]);
            }
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < ListBox2.Items.Count; i++)
        {
            if (ListBox2.Items[i].Selected)
                ListBox2.Items.RemoveAt(i);
        }
    }
    protected void btUploadImage_Click(object sender, EventArgs e)
    {
        try
        {
            if (ImageUpload.HasFile && lbTypePath.Text != "" && lbTypePath.Text != "{0}")
            {
                HttpCookie ck = Request.Cookies["major"];
                string savepath = ck.Values["majorid"] + "/" + lbTypePath.Text + "/preview/";
                myUpload upload = new myUpload(ImageUpload, savepath);
                preImage.ImageUrl = upload.filePath;
                PackageImage.ImageZip(200, 135, upload.filePath);
            }
            else
            {
                throw new Exception("没有选择文件或保存目录。");
            }
        }
        catch (Exception ex)
        {
            Response.Write("<script >function window.onload() {alert('" + ex.Message.ToString() + "');}</script>");
        }
    }
}
